package com.deer.backup.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.deer.backup.result.PageDomain;
import com.deer.backup.result.Result;
import com.deer.backup.result.ResultController;
import com.deer.backup.result.ResultTable;
import com.deer.backup.service.BackUpService;
import com.deer.backup.utils.CommonUtils;
import com.deer.backup.utils.SshjUtils;
import com.deer.backup.vo.BackUp;
import com.deer.backup.vo.RemoteVo;

import cn.hutool.core.date.DateUtil;
import lombok.extern.slf4j.Slf4j;
import net.schmizz.sshj.SSHClient;

@Slf4j
@RestController
@RequestMapping("/backup")
public class BackUpController extends ResultController{
	
    @Autowired
    private BackUpService backUpService;

    //列表主页面
    @GetMapping("/main")
    public ModelAndView mainview(Model model) {
    	return jumpPage("backup/main");
    }
    
    //添加主页面
    @GetMapping("/edit")
    public ModelAndView editview(Long id, ModelMap map) {
    	BackUp backup = new BackUp();
    	if(id != null) {
    		backup = backUpService.getBackUpById(id);
    	}
    	map.put("backup", backup);
        return jumpPage("backup/edit");
    }
    
    @ResponseBody
    @GetMapping("data")
    public ResultTable data(PageDomain page) {
    	Page<BackUp> pageInfo = backUpService.findBackUp(page);
    	return pageTable(pageInfo.getContent(), pageInfo.getTotalElements());
    }

    // 更新指定ID的BackUp数据
    @ResponseBody
    @PutMapping("/update")
    public Result<?> updateBackUpById(@RequestBody BackUp backUp) {
        return decide(backUpService.updateBackUp(backUp));
    }

    // 删除指定ID的BackUp数据
    @DeleteMapping("/delete/{id}")
    public Result<?> deleteBackUpById(@PathVariable Long id) {
        backUpService.deleteBackUpById(id);
        return decide(true);
    }

    /**
    * @description 立即启动备份
    * @author deer
    * @date 2023-06-15 14:49:49
    * @param 
    * @return 
    */
    @ResponseBody
    @GetMapping("/startBackUp")
    public Result<?> startBackUp(Long id) {
        BackUp backUp = backUpService.getBackUpById(id);
        new Thread(() -> {
            try {
                RemoteVo remote = new RemoteVo();
                remote.setHost(backUp.getServerHost());
                remote.setUser(backUp.getServerUser());
                remote.setPassword(backUp.getServerPwd());
                SSHClient sshClient = SshjUtils.getConnect(remote);
                if (sshClient.isConnected()) {
                    log.info(DateUtil.now() + "==>开始执行 " + backUp.getName() + " 任务");
                    // 生成文件名称
                    String backUpFile = backUp.getBackupName() + ".tar.gz";
                    // 压缩home文件夹
                    SshjUtils.remoteExecute(sshClient, "tar -zcvf " + backUpFile + " " + backUp.getServerPath());
                    SshjUtils.sftpDownload(sshClient, "/root/" + backUpFile , CommonUtils.createDir(backUp.getDirPath()) + "/" + backUpFile);
                    // 删除服务端压缩包
                    SshjUtils.remoteExecute(sshClient, "rm -f " + backUpFile);
                    // 关闭连接
                    sshClient.disconnect();
                    log.info(DateUtil.now() + "==>完成 " + backUp.getName() + " 任务");
                } else {
                    log.error(backUp.getServerHost()+" 连接失败！");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }).start();
    	return decide(true);
    }
}